import React from 'react'
import {connect} from 'react-redux'
// import axios from 'axios'
import {request} from '../../utils/request'
import { NavBar, Icon ,Toast} from 'antd-mobile';
import css from './index.module.scss'

import {List} from 'react-virtualized';
class CitySelect extends React.Component {
    constructor(){
        super();
        this.ListRef=React.createRef()
    }
    state={
        //s=城市列表
        finallList:[],
        //字母列表
        letterList:[],
        currentIndex:0,
    }
   async  componentDidMount(){
       //用于试图渲染的列表数据
       let finallList=[]
        //当前城市
        const cityName=this.props.cityName
        finallList.push({
            title:'当前城市',
            children:[{city:cityName}]
        }) 
        // console.log(finallList);
        //使用Promise.all优化请求
        const res=await Promise.all([request.get('/area/hot'),request.get('/area/city?level=1')])
        //热门城市
        const cityHot=res[0].data.body
        const cityList=res[1].data.body
        // const cityHot=(await request.get('/area/hot')).data.body
        finallList.push({
            title:'热门城市',
            children:cityHot.map(v=>({city:v.label}))
        })
            console.log(finallList);    
          //城市列表
        //   const cityList=(await request.get('/area/city?level=1')).data.body
          //城市排序
        cityList.sort((a,b)=>a.short>b.short?1:-1)
           console.log(cityList);
           cityList.forEach(item=>{
               //拿到城市字母的首字母在转换为大写
               const firstLetter=item.short.charAt(0).toUpperCase()
            //    console.log(firstLetter);
               //还得判断首字母是否属于编组,如果不是就创建新的编组
               //findIndex:如果没有返回-1
               const index=finallList.findIndex(item=>item.title===firstLetter)
               if(index===-1){
                finallList.push({
                    title:firstLetter,
                    children:[{city:item.label}]
                })
               }else{
                   //存在编组的话,加入到children中
                   finallList[index].children.push({city:item.label})
               }
           })
           //输出看看编组好后的新的数组数据
        //    console.log(finallList);
        //把finallList更新到页面中
        let letterList=finallList.map(v=>v.title)
        letterList.splice(0,2,'#','热')
        // console.log(letterList);
        this.setState({finallList,letterList})
        // console.log(this.ListRef.current);
        this.ListRef.current.measureAllRows()
        
    }
    //改变字母列表的索引值
    changeIndex=(currentIndex)=>{
        // console.log(currentIndex);
        this.ListRef.current.scrollToRow(currentIndex) 
        this.setState({currentIndex})    
    }
    //一大行高度:标题高+孩子长度*孩子高度
    rowHeight=({index})=>{
        const {finallList}=this.state
        return finallList[index].children.length*40+40
    }
    //点击长列表每一个数据触发的事件
    getCurrentCity=(currentCity)=>{
        const {finallList}=this.state
        // console.log(currentCity);
        const hotCity=finallList[1].children
        const index=hotCity.findIndex(item=>(item.city===currentCity))
        // console.log(index);
        //除了热门城市其他都没有房源
        if(index===-1){
            Toast.info('该城市没有房源信息')
        }else{
            this.props.changeStoreCity(currentCity)
            this.props.history.goBack()
        }
    }
    getCurrentCity
    //行渲染函数
    rowRenderer=({key,index,style})=>{
        const {finallList}=this.state
        return(
            <div className={css.city_group} key={key} style={style}>
                  <div className={css.city_group_title}> {finallList[index].title}</div>
                {
                 finallList[index].children.map(item=>(
                 <div className={css.city_group_item} key={item.city} onClick={()=>this.getCurrentCity(item.city)}>{item.city}</div>
                 ))

                }
            </div>
        )
    }
    //城市列表的列表位置的改变字母列表也跟着改变
    onRowsRendered=({startIndex})=>{
        //用if优化
        if(this.state.currentIndex===startIndex) return;
       this.setState({currentIndex:startIndex})
    }
    render() { 
        const {finallList,letterList,currentIndex}=this.state
        // console.log(this.props);
        return (
            // <div>CitySelect页面内容</div>
        <div className={css.city_select}> 
    <NavBar
      mode="light"
      icon={<Icon type="left" />}
      onLeftClick={() =>this.props.history.goBack()}
     >城市选择
    </NavBar>
    {/* 所有城市的列表渲染 */}
    <div className={css.city_all}>
        {
            <List
            ref={this.ListRef}
            //这样可以获取屏幕宽度的100%
    width={window.screen.width}
     //这样可以获取屏幕高度的100%
    height={window.screen.height - 45}
    rowCount={finallList.length}
    rowHeight={this.rowHeight}
    rowRenderer={this.rowRenderer}
    scrollToAlignment='start'
    //会冲突,用另外一种
    // scrollToIndex={currentIndex}
    onRowsRendered={this.onRowsRendered}
  />
            // finallList.map(item=>(
            //     <div key={item.title} className={css.city_group}>
            //     <div className={css.city_group_title}>{item.title}</div>
            //    {
            //        item.children.map(item2=>(
            //        <div key={item2.city} className={css.city_group_item}>{item2.city}</div>
            // ))
            //    }
            //     </div>
            // ))
        }
       
    </div>
{/* 右侧字母 */}
<div className={css.letter}>
    {
        letterList.map((item,index)=>(
<div onClick={()=>this.changeIndex(index)} key={item} className={css.letter_item}>
        <span className={currentIndex===index?css.active:''}>{item}</span>
    </div>
        ))
    }
    
</div>
    </div>
        );
    }
}
 
const mapStateToProps=(state)=>({
    cityName:state.address.city
})
//修改
const mapDispatchToProps=(dispatch)=>({
    changeStoreCity:(currentCity)=>{
        console.log(currentCity);
        const action={
             type:'change_city',
             value:{
                 city:currentCity
             } 
        }   
        dispatch(action)
    }
})
export default connect(mapStateToProps,mapDispatchToProps)(CitySelect);